﻿namespace SPTaxonomyClient.Taxonomy
{
	using System.Text;
	using Microsoft.SharePoint.Client;
	using System;

	/// <summary>
	/// This class represents a term that will be assigned as a value of a TaxonomyField on a File item in a document library.
	/// It must be initialized with a Term and a ClientContext that targets a specific Web.
	/// </summary>
	/// <see cref="Term"/>
	/// <see cref="Microsoft.SharePoint.Client.ClientContext"/>
	public class TaxonomyFieldValue
	{
		#region Fields
		private readonly ClientContext _clientContext;
		private int _wssId;
		private readonly Term _term;
		#endregion

		//private string notWellFormatedError =
		//	"La valeur fournie pour un champ de taxonomie n’a pas été mise en forme au format <int>;#<label>|<guid> requis.";

		/// <summary>
		/// Initializes the Taxonomy value
		/// </summary>
		/// <param name="term">A term from a <see cref="TermSet"/></param>
		/// <param name="clientContext"></param>
		public TaxonomyFieldValue(Term term, ClientContext clientContext)
		{
			_term = term;
			// TODO : Ensure the context targets a Web
			_clientContext = clientContext;
		}
		
		/// <summary>
		/// Returns a textual representation of the TaxonomyFieldValue. This does the main part that allows
		/// assigning a tag to a File item.
		/// </summary>
		/// <returns> A value of the form &lt;int&gt;;#&lt;label&gt;|&lt;guid&gt;</returns>
		public override string ToString()
		{
			if (_clientContext == null)
			{
				throw new ApplicationException("The SharePoint client context isn't initialized properly.");
			}
			List taxonomyList = _clientContext.Web.Lists.GetByTitle("TaxonomyHiddenList");
				_clientContext.Load(taxonomyList);

				CamlQuery camlQuery = new CamlQuery
				{
					ViewXml = string.Format(
						@"
<View>
	<Query>
		<Where>
			<Eq>
				<FieldRef Name='IdForTerm' />
				<Value Type='Text'>{0}</Value>
			</Eq>
		</Where>
	</Query>
</View>", _term.Id)
				};
				ListItemCollection itemCollection = taxonomyList.GetItems(camlQuery);
				_clientContext.Load(itemCollection);
				_clientContext.ExecuteQuery();
				_wssId = itemCollection.Count == 1 ? int.Parse(itemCollection[0]["ID"].ToString()) : -1;


			StringBuilder builder = new StringBuilder();
			if (_term != null)
			{
				builder.Append(_wssId + ";#");
				builder.Append(_term.Name);
				builder.Append(TaxonomyField.TaxonomyGuidLabelDelimiter);
				builder.Append(_term.Id);
			}
			return builder.ToString();
		}
	}
}
